package com.weiwu.weiwustore.security.bean;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.weiwu.weiwustore.entity.Apply_record;
import com.weiwu.weiwustore.entity.Role;
import com.weiwu.weiwustore.entity.Store;
import com.weiwu.weiwustore.entity.User;
import com.weiwu.weiwustore.exception.MyException;
import com.weiwu.weiwustore.mapper.Apply_recordMapper;
import com.weiwu.weiwustore.mapper.RoleMapper;
import com.weiwu.weiwustore.mapper.StoreMapper;
import com.weiwu.weiwustore.pojo.UserDto;
import com.weiwu.weiwustore.pojo.VersionVo;
import com.weiwu.weiwustore.pojo.WelcomVo;
import com.weiwu.weiwustore.security.pool.AuthenticationTokenPool;
import com.weiwu.weiwustore.service.UserService;
import com.weiwu.weiwustore.utils.Md5;
import com.weiwu.weiwustore.utils.ObjectFormatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 内置多种登录方式，和shiro中的realm类似
 */
@Component
public class LoginRealms {
    @Autowired
    private UserService userService;
    @Autowired
    StoreMapper storeMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    Apply_recordMapper apply_recordMapper;

    /**
     * 认证，如果认证成功则返回凭证，否则返回null
     *
     * @param userToken 未认证的令牌
     * @return 如果认证成功则返回凭证，否则返回null
     */
    public String authenticate(UserToken userToken) {
        if (userToken.getCredentials() != null) {
            //对密码加密
            userToken.setCredentials(Md5.crypt(userToken.getCredentials()));
        }
        if (userToken.getLoginType().equals(LoginType.EMAIl_PASSWORD)) {
            return handle(userToken, emailLogin(userToken));
        }
        //如果无匹配的认证方式则视为验证失败
        return null;
    }

    public UserDto getUserName(UserToken userToken) {
        User user = userService.findUserByEmail(userToken.getPrincipal());
        String StoreStr = "暂无";
        Store store;
        // 格式化显示所负责的仓库
        if (user.getStoreid() != null) {
            store = storeMapper.selectById(user.getStoreid());
            StoreStr = store.getSname();
        }
        // 格式化显示角色
        Role role = roleMapper.selectById(user.getRoleid());
        return new UserDto(user.getId(), user.getUname(), StoreStr, role.getRole(), user.getEmail(), user.getStoreid());
    }

    /**
     * 邮箱登录方式
     *
     * @param userToken 令牌
     * @return 认证成功返回SimpleUser
     */
    private User emailLogin(UserToken userToken) {
        return userService.findUserByEmail(userToken.getPrincipal());
    }

    /**
     * 根据传入的user是否为null（是否认证通过）来对令牌做剩下的操作（将user刻入令牌，并将该令牌放入令牌池中）
     *
     * @param userToken 经过验证后的令牌
     * @return token 根据令牌生成的凭证 ，如果认证未成功则返回null
     */
    private String handle(UserToken userToken, User user) {
        if (user == null) {
            //说明账户不存在
            throw new MyException(409, "该用户不存在，请注册后再登录！");
        }
        //判断账号是否加入了仓库
        if (user.getStoreid() == null) {
            throw new MyException(409, "此账号未加入仓库，请联系仓库管理员加入");
        }
        //判断密码是否正确
        if (user.getPwd().equals(userToken.getCredentials())) {
            //将UserP信息刻入令牌
            userToken.setUser(userService.singlePack(user));
            //获取token凭证
            String token = Md5.crypt(userToken.getPrincipal() + userToken.getInstant());
            //将令牌放入认证令牌池
            AuthenticationTokenPool.addToken(token, userToken);
            return token;
        }
        return null;
    }

    public WelcomVo getwelcome(Map<String, String> map) {
        Integer userid = ObjectFormatUtil.toInteger(map.get("id"));
        Integer applycount = apply_recordMapper.selectCount(
                new QueryWrapper<Apply_record>().eq("applicantid",userid));
        Integer reviewercount = apply_recordMapper.selectCount(
                new QueryWrapper<Apply_record>().eq("reviewerid",userid));
        Integer checkercount = apply_recordMapper.selectCount(
                new QueryWrapper<Apply_record>().eq("checkerid",userid));
        Random num = new Random();
        String content = "";
        switch (num.nextInt(5)) {
            case 0:
                content= "宁得罪君子，不得罪小人。不要公开反对或者得罪他们，保持适当距离就好。处在差不多同等阶级的话，君子永远斗不过小人。";
                break;
            case 1:
                content="明天有多远，我又会遇见，多少个美丽的明天。";
                break;
            case 2:
                content= "一寸光阴一寸金，寸金难买寸光阴。";
                break;
            case 3:
                content="别急，时间公平，只看你怎么操作你的人生。努力了，虽然不尽入人意，但总会有一些收获。";
                break;
            case 4:
                content= "任世间纷杂，努力做一个简单的人";
                break;
            default:
                content= "大家都在辛苦谋生，我又有什么理由不努力生活呢？";
                break;
        }
        return new WelcomVo(applycount,reviewercount,checkercount,content);
    }

    public VersionVo getversion() {
        return new VersionVo("唯物仓库管理系统", "1.0", "刘神龙", "2998690636@qq.com");
    }
}
